import os
import csv
import glob
from collections import defaultdict

def extract_gcc_config(file_path):
    """
    从文件中提取GCC配置参数
    
    Args:
        file_path (str): 文件路径
    
    Returns:
        dict: 参数名到值的映射
    """
    config = {}
    with open(file_path, 'r') as f:
        for line in f:
            if line.startswith('Configured with:'):
                # 提取配置字符串
                config_str = line.split('Configured with:', 1)[1].strip()
                
                # 分割参数
                tokens = config_str.split()
                for token in tokens:
                    if token.startswith('--'):
                        # 处理带等号的参数
                        if '=' in token:
                            key, value = token.split('=', 1)
                            config[key] = value
                        # 处理不带等号的参数
                        else:
                            config[token] = 'True'
                break
    return config

def generate_config_csv(output_path):
    """
    生成GCC配置的CSV文件
    
    Args:
        output_path (str): 输出CSV文件路径
    """
    # 获取所有txt文件
    input_dir = os.path.join(os.path.dirname(__file__), '..', 'makeout')
    txt_files = glob.glob(os.path.join(input_dir, '*.txt'))
    
    # 收集所有配置数据和参数名
    all_configs = {}
    all_params = set()
    
    for file_path in txt_files:
        # 获取文件名作为记录名
        record_name = os.path.splitext(os.path.basename(file_path))[0]
        config = extract_gcc_config(file_path)
        
        # 保存配置并收集参数名
        all_configs[record_name] = config
        all_params.update(config.keys())
    
    # 对参数名排序
    sorted_params = sorted(all_params)
    
    # 写入CSV文件
    with open(output_path, 'w', newline='') as csvfile:
        writer = csv.writer(csvfile)
        
        # 写入表头
        header = ['record'] + sorted_params
        writer.writerow(header)
        
        # 写入每行数据
        for record_name, config in all_configs.items():
            row = [record_name]
            for param in sorted_params:
                row.append(config.get(param, ''))
            writer.writerow(row)

if __name__ == "__main__":
    # 输出文件路径
    output_csv = os.path.join(os.path.dirname(__file__), 'gcc_configs.csv')
    generate_config_csv(output_csv)
    print(f"配置已成功导出到: {output_csv}")
